package examples.socket;

import java.net.*;
import java.io.*;

/**
 *
 * @author prabhat.totoo
 */
public class ConfusedClient {

    public static void main(String args[]) {

        Socket client = null;
        BufferedReader socketReader  = null;
        BufferedReader consoleReader = null;
        PrintStream    socketWriter  = null;
        String         clientLine    = null;
        String         serverLine    = null;
        boolean        bDone         = false;

        try {

            /* Remember the port number is 8313.  The host here
            * is the IP address for your machine.  How did I know
            * you ask?  Well, all machines loop that IP address
            * back to itself.
            */
            client = new Socket(args[0], 8313);

            /* In order to create the BufferedReader, we need
            * to wrap the InputStream in an InputStreamReader
            */
            socketReader = new BufferedReader(new InputStreamReader(client.getInputStream()));

            /* We are using a PrintStream so that we can use the
            * same methods we always use for printing.
            */
            socketWriter = new PrintStream(client.getOutputStream());

            /* Need to set up reading from the console
            */
            consoleReader = new BufferedReader(new InputStreamReader(System.in));
            clientLine = consoleReader.readLine();

            while(!bDone && (clientLine != null)) {
                socketWriter.println(clientLine);

                if(clientLine.equalsIgnoreCase("exit")) {
                    bDone = true;
                }
                else {
                    serverLine = socketReader.readLine();
                    System.out.println("Response: " + serverLine);

                    /* Need to read the next line */
                    clientLine = consoleReader.readLine();
                }
            }

            socketReader.close();
            socketWriter.close();
            client.close();
        }
        catch(UnknownHostException uhe) {
            System.out.println("Could not connect to host");
        }
        catch(IOException ioe) {
            System.out.println("I/O Exception occurred while using the socket.");
        }

        System.out.println("Client is going home...");
    }

}